import { getCategory } from '@/api/category'
import { ALL_CATEGORY_ITEM, CATEGORY_NOMAR_DATA } from '@/constants'
import { useAppStore } from './app'
import { parse, stringify } from 'zipson'
import { defineStore } from 'pinia'

export const useCategoryStore = defineStore('categoryStore', {
  state: () => ({
    // navigationBar 展示的数据源
    categorys: CATEGORY_NOMAR_DATA,
  }),
  getters: {
    /**
     * navigationBar 数据源
     */
    categorys: (state) => state.categorys,
    /**
   * category选中项下标
   */
  currentCategoryIndex: (state) => {
    const appStore=useAppStore()
    return state.categorys.findIndex(
      (item) => item.id === appStore.currentCategory.id
    )
  },
  },
  actions: {
    /**
     * 为 categorys 赋值
     */
    setCategorys(categorys: any) {
      this.categorys = [ALL_CATEGORY_ITEM, ...categorys]
    },
    /**
     * 获取 category 数据，并自动保存到 vuex 中
     */
    async useCategoryData() {
      const { categorys } = await getCategory()
      this.setCategorys(categorys)
    },
  },
  persist: {
    key: 'categoryStore',
    storage: localStorage,
    serializer: {
      deserialize: parse,
      serialize: stringify,
    },
  },
})
